import { IPage } from '@/service/types';
import { defineStore } from 'pinia';
import { System, useSystemRepository } from './system-repository';

export const STORE_KEY_PROJECT = 'store-project';

export type Project = {
  id?: string;
  name: string;
  description: string;
  start: string;
  end: string;
};

export const useProjectStore = defineStore(
  STORE_KEY_PROJECT,
  () => {
    const systemRepository = useSystemRepository();

    const projectSystems = ref<Array<{ projectId: string; systemId: string }>>([
      {
        projectId: '2bca09d1-c4c3-4d0f-a770-a9ea52133870',
        systemId: '8f12a674-82ac-4c8d-ae90-a70a068accf9',
      },
      {
        projectId: '59b77efd-690f-4990-9fe5-ef21d6350bd2',
        systemId: 'b486459c-30eb-4af0-8626-a95959667d51',
      },
    ]);
    const projects = ref<Array<Project>>([
      {
        id: '2bca09d1-c4c3-4d0f-a770-a9ea52133870',
        name: '工作流平台一期',
        description: '提供流程生命周期管理的平台级服务',
        start: '2024-05-10',
        end: '--',
      },
      {
        id: '59b77efd-690f-4990-9fe5-ef21d6350bd2',
        name: '文档平台一期',
        description: '提供文档管理的平台级服务',
        start: '2024-10-01',
        end: '--',
      },
    ]);

    const systems = (projectId: string): Promise<IPage<System>> => {
      return new Promise(resolve => {
        resolve({
          current: 1,
          size: 10,
          records: projectSystems.value
            .filter(projectSystem => {
              return projectSystem.projectId == projectId;
            })
            .map(projectSystem => {
              return systemRepository.getSystem(projectSystem.systemId)!;
            }),
        });
      });
    };

    const addProject = (project: Project) => {
      projects.value = [project].concat(projects.value);
    };

    const getProject = (projectId: string) => {
      const projects_ = projects.value;
      for (let i = 0; i < projects_.length; i++) {
        const project_ = projects_[i];
        if (project_.id == projectId) {
          return project_;
        }
      }
      return undefined;
    };

    return { projects, systems, addProject, getProject };
  },
  {
    persist: {
      key: STORE_KEY_PROJECT,
      storage: localStorage,
    },
  },
);
